procedure bfs(v:longint); {A - Matrix; N - number of points}
var i,head,tail:longint; was:array[1..n] of boolean; q:array[1..n] of longint;
begin
head:=1;
tail:=1;
q[tail]:=v;
was[v]:=true;
while head<=tail do begin
  for i:=1 to n do begin
    if (a[v][i]<>0) and (not was[i]) then begin
      inc(tail);
      q[tail]:=i;
      was[i]:=true;
    end;
  end;
  inc(head);
  v:=q[head];
end;
end;